// pages/upload/upload.js
import {location} from '../../api/location.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryData: [],
    index:0,
    address:'未选择',
    title:'',
    latitude:0,
    longitude:0,
    desc:"",
    upload:'/resource/images/upload.png'
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  // 数据提交
  async formSubmit(e) {
    wx.showLoading({
      title: '正在提交中...',
    })
    console.log(e)
    let params = {
      type:e.detail.value.type,
      latitude:this.data.latitude,
      longitude:this.data.longitude,
      name:e.detail.value.name,
      phone:e.detail.value.phone,
      desc:e.detail.value.desc,
      thumb:e.detail.value.thumb,
      address:e.detail.value.address,
      title:e.detail.value.title,
      sort:+new Date()
    }
    const {result} = await location.addCat(params)
    wx.hideLoading()
    if(result.errMsg === 'collection.add:ok'){
      wx.showModal({
        title: '数据提交成功',
        content: '是否跳转到导览页',
        success (res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1,
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    }
    console.log(result)
  },
  // 选择位置
  openLocation(){
    wx.getLocation({
      type: 'wgs84',
      success:({latitude, longitude, speed,accuracy})=> {
        wx.chooseLocation({
          latitude,
          longitude,
          success: ({ latitude, longitude, address,name})=> {
            console.log(latitude, longitude, address, name)
            this.setData({
              title:name,
              address,
              latitude,
              longitude
            })
          },
        })
      }
    })
  },
  // 上传图片
  async chooseImage() {
    const {tempFilePaths} = await wx.chooseImage({
      count: 9,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],
    })
    wx.showLoading({ title: '上传中...'  })
    const {fileID} = await wx.cloud.uploadFile({
      cloudPath:+new Date() + '_icon.png',
      filePath:tempFilePaths[0],
    })
    wx.hideLoading()
    this.setData({ upload: fileID })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad (options) {
    // 获取分类
    const {result:{data}} = await location.queryCat();
    this.setData({
      categoryData:data
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})